package xkp.lesson.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import xkp.lesson.entity.Emp;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload.action")
    public String upload(MultipartFile[] file, Emp emp, HttpServletRequest request) throws IOException {
        System.out.println(emp);
        String rootPath = request.getServletContext().getRealPath("/upload");
        File dir = new File(rootPath);
        if(!dir.exists()){
            dir.mkdirs();
        }


        for(MultipartFile thisFile:file){
            String fileName = thisFile.getOriginalFilename();
            thisFile.transferTo(new File(rootPath+File.separator+fileName));
        }
        /*String fileName = file.getOriginalFilename();
        file.transferTo(new File(rootPath+File.separator+fileName));*/
        return "redirect:/index.jsp";
    }

    @GetMapping("/download.action")
    public void downLoad(HttpServletRequest request, HttpServletResponse response,  String fileName) throws IOException {
        String rootPath = request.getServletContext().getRealPath("/upload");

        String name = URLEncoder.encode(fileName,"UTF-8");
        response.addHeader("content-disposition", "attachment;fileName="+name);
        File file = new File(rootPath+File.separator+fileName);
        FileInputStream inputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();
        byte[] buf = new byte[1024];
        int n = inputStream.read(buf);
        while(n != -1){
            outputStream.write(buf,0,n);
            n = inputStream.read(buf);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }
}
